import glob
import importlib
import os
from enums import parse_dict_enum
from tools import underline_to_hump


class LoadEnum:
    """
    加载字典
    """

    def __init__(self, app=None):
        self.app = app
        if app:
            self.init_app(app)

    def init_app(self, app):
        self.app = app
        app.config['DICT_ENUM_MAP'] = {}
        app.config['DICT_ENUM_LIST'] = []
        # 获取controllers目录下所有的.py文件路径
        enums_dir = 'enums'
        enum_files = glob.glob(os.path.join(enums_dir, '*.py'))
        # 过滤掉__init__.py文件
        enum_files = [f for f in enum_files if ('__init__.py' not in f and 'load_enum.py' not in f)]
        for file_path in enum_files:
            module_name = os.path.splitext(os.path.basename(file_path))[0]  # 去掉'.py'后缀
            module_path = f'enums.{module_name}'
            try:
                enum_module = importlib.import_module(module_path)
                enumClass = getattr(enum_module, underline_to_hump(module_name)) 
                enumData = parse_dict_enum(enumClass)
                dictKey = enumData.get('dictKey')
                app.config['DICT_ENUM_MAP'].update({dictKey: enumData})
                app.config['DICT_ENUM_LIST'].append(enumData)
            except (ImportError, AttributeError) as e:
                print(f"Failed to load model {module_name}: {e}")
        